package com.lhd.controller;

import com.lhd.config.AliSMSConfig;
import com.lhd.pojo.Result;
import com.lhd.pojo.User;
import com.lhd.service.UserService;
import com.lhd.utils.AliSMSUtils;
import com.lhd.utils.JwtUtil;
import com.lhd.utils.ThreadLocalUtil;
import com.lhd.utils.ValidateCodeUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    AliSMSUtils aliSMSUtils;
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        System.out.println(user);
        User realUser = userService.login(user);
        if (realUser == null){
            return Result.error("用户不存在或密码错误");
        }
        System.out.println(realUser);
        //发放令牌
        Map<String, Object> map = new HashMap<>();
        map.put("id",realUser.getId());
        String token = jwtUtil.genToken(map);
        //将令牌存入redis
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set("token",token,10, TimeUnit.HOURS);
        return Result.success(token);
    }
    @PostMapping("/register")
    public Result register(@RequestBody User user){

        userService.register(user);
        return Result.success();
    }
    @DeleteMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token){
        System.out.println(token);
        deleteToken(token);
        return Result.success();
    }
    @GetMapping("/getCode")
    public Result phoneLogin(String phone){
        //生成验证码 发短信 将验证码返回给前端
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        System.out.println(phone + "/" + code);
        Map<String, Object> map = new HashMap<>();
        map.put("code",code);
        System.out.println(aliSMSUtils.send(map,phone));
        return Result.success(code);
    }

    public void deleteToken(String token){
        RedisOperations<String, String> operations = redisTemplate.opsForValue().getOperations();
        operations.delete(token);
    }
}
